import json
from common.log import logger
from common.globalcontenxt import GlobalContext
from common.read import read
from common.AssertUtil import AsserUtil
from common.YamlUtil import YamlUtil
from common.conmysql import db
from testcase.ordercenter.conftest import get_orderid
class ExtractUtil:
    def __init__(self):
        self.jsonpath_util = AsserUtil()
        self.yaml_util = YamlUtil()
        self.globalc = GlobalContext()
    def extract_data(self,res,extarct):
        """

        :param res: res.json()
        :param extarct: $.token
        :return:
        """
        if extarct:
            for key,expression in extarct.items():
                try:
                    value = self.jsonpath_util.expect_by_jsonpath(res, expression)
                    logger.info(f'value是{value}')
                    # 写入extract.yaml文件
                    self.yaml_util.write_extra_yaml({key: value})
                    self.globalc.set_dict({{key: value}})
                    logger.info(f'jsonpath表达式：{expression}提取数据存全局变量{key}：{value}成功！')
                except Exception as e:
                    logger.error(f"从yaml根据{key}获取不到内容，error={e}")

                # if "(" in expression and ")" in expression:
                #     func_name = expression[expression.index("$") + 2: expression.index("}")]
                #     eval(func_name + "()")
                # else:

    def extract_data_new(self, res, extarct):
        """

        :param res: res.json()
        :param extarct: $.token
        :return:
        """
        if extarct:
            for key, expression in extarct.items():
                try:
                    value = self.jsonpath_util.expect_by_jsonpath(res, expression)
                    logger.info(f'value是{value}')
                    # 写入extract.yaml文件
                    # self.yaml_util.write_extra_yaml({key: value})
                    self.globalc.set_dict({key: value})
                    logger.info(f'jsonpath表达式：{expression}提取数据存全局变量{key}：{value}成功！')
                except Exception as e:
                    logger.error(f"jsonpath表达式：{expression}提取值失败，error={e}")


   #这里的data可以是uri是str类型，也可以是json等参数的dic类型
    def process_data(self,data):
        #处理函数
        # 接口请求参数，params，json，data
        for i in range(data.count("${")):
        # / orders /${get_extract_value(order_id)} /
            if "${" in data and "}" in data:
                start_index = data.index("$")
                #str.index(str,starindex,endindex)可以指定从索引位置查找
                end_index = data.index("}",start_index)
                #获取函数中的方法
                func_full_name = data[start_index:end_index+1]
                #获取函数名
                func_name = data[start_index+2:data.index("(")]
                #获取函数中参数
                func_params = data[data.index("(")+1:data.index(")")]
                #反射getattr(),只支持函数参数为str
                #如果有参数则执行前面解包要是没有参数就给空
                extract_data = getattr(self,func_name)(*func_params.split(",") if func_params else "")
                if not isinstance(extract_data,list):
                    extract_data = [extract_data]
                data = data.replace(func_full_name, str(extract_data[0]))
        return data

    #json参数中字典格式获取${}中的值
    def extract_case(self,case_info):
        #把dic转出str
        str_case_info = json.dumps(case_info)
        data = self.process_data(str_case_info)
        #换回dic类型
        return json.loads(data)

    #从extract.yaml中读取内容
    def get_extract_value(self,key):
        try:
            data = self.yaml_util.read_extra_yaml()
            return data[key]
        except Exception as e:
            logger.error(f"从yaml中根据{key}获取不到内容，error={e}")

    # 从读取内容下单页地址信息拼接详情地址
    def get_address(self):
        province = YamlUtil().read_extra_yaml()["province"]
        city = YamlUtil().read_extra_yaml()["city"]
        district = YamlUtil().read_extra_yaml()["district"]
        address = YamlUtil().read_extra_yaml()["address"]
        address_detail = province + city + district + address
        YamlUtil().write_extra_yaml({"address_detail": address_detail})
        return address_detail

    # 从conftest.py中读取内容下单后的订单id
    def get_orderid(self):
        return get_orderid()

    #读取img图片内容
    def get_read_img(self):
        try:
            files = read.read_img()
            return files
        except Exception as e:
            logger.error(f"读取img图片内容失败，error={e}")
    #获取uri
    def extract_url(self,uri):
        if "${" in uri and "}" in uri :
            return self.process_data(uri)
        return uri

    #读取data.yaml文件中的goodsid
    def get_goodsid(self):
       goodsid= read.read_yaml()["goodsid"]
       return goodsid